const fs = require('fs');
const path = require('path');
const { decrypt, encrypt, findFilePath } = require('./tool.js');
const sourceDirPath = ['./data', './bg'].map((p) => {
  return path.resolve(__dirname, p);
});
const allDatFiles = [];
for (let sourcePath of sourceDirPath) {
  findFilePath(sourcePath, '.dat', '_code', allDatFiles);
}
const waitToWriteMap = {};
console.table(allDatFiles);

function checkFilesIsDecode() {
  for (let p of allDatFiles) {
    let content = fs.readFileSync(p);
    const firstCharacter = content.slice(0, 8).toString();
    if (firstCharacter[0] !== '<') {
      content = decrypt(content);
      fs.writeFileSync(p, content);
    }
    const toEncodeFilePath = p.replace('_code', '');
    fs.writeFileSync(toEncodeFilePath, encrypt(content));
  }
}

function watchFileToEncode() {
  for (let sourcePath of sourceDirPath) {
    const ws = fs.watch(sourcePath, {
      recursive: true,
    });
    ws.on('change', function (e, filename) {
      if (e === 'change' && filename.indexOf('_code') > -1) {
        clearTimeout(waitToWriteMap[filename]);
        waitToWriteMap[filename] = setTimeout(() => {
          const toEncodeFileName = filename.replace('_code', '');
          const codeFilePath = path.resolve(sourcePath, filename);
          const toFilePath = path.resolve(sourcePath, toEncodeFileName);
          console.log('encode', new Date().toLocaleTimeString(), codeFilePath, '->', toFilePath);
          let content = fs.readFileSync(codeFilePath);
          const firstCharacter = content.slice(0, 8).toString();
          if (firstCharacter[0] !== '<') {
            content = decrypt(content);
            fs.writeFileSync(codeFilePath, content);
          }
          fs.writeFileSync(toFilePath, encrypt(content));
        }, 1000);
      }
    });
  }
}

function run() {
  checkFilesIsDecode();
  watchFileToEncode();
}

run();
